package com.sskj.hangqing.presenter;

import com.google.gson.Gson;
import com.lzy.okgo.model.Response;
import com.sskj.common.base.HttpData;
import com.sskj.common.http.WebSocketObserver;

import com.sskj.lib.Constans;
import com.sskj.lib.bean.SocketSendBean;
import com.sskj.lib.http.JsonCallBack;
import com.sskj.hangqing.bean.PushTradeBean;
import com.sskj.hangqing.bean.TradeBean;
import com.sskj.hangqing.http.HttpConfig;
import com.sskj.hangqing.ui.fragment.TradeFragment;
import com.sskj.lib.util.CommonUtil;

import java.util.List;

import io.reactivex.disposables.Disposable;


public class TradeFragmentPresenter extends BasePresenter<TradeFragment> {

    private WebSocketObserver stockSocket;
    private Disposable stockDisposable;
    private String code;

    public void getData(String code) {
//        httpService.getAllTrade(code)
//                .execute(new JsonCallBack<HttpData<List<TradeBean>>>() {
//                    @Override
//                    public void onSuccess(Response<HttpData<List<TradeBean>>> response) {
//                        HttpData<List<TradeBean>> httpData = response.body();
//                        if (httpData.getStatus() == HttpConfig.OK) {
//                            mView.updateUI(httpData.getData());
//
//                        }
//                    }
//                });
    }

    public void initSocket(String code) {
        if (code==null)
            return;
        code= CommonUtil.dealReuqestCode(code);
        if (stockSocket == null) {
            stockSocket = httpService.pushCoinTrade(code);
            stockDisposable = stockSocket
                    .map(s -> new Gson().fromJson(s, PushTradeBean.class))
                    .subscribe(data -> mView.updateData(data), e -> {
                    });

        } else {
            stockSocket.send("{\"unsub\":\"trader."+this.code+"\"}");
            stockSocket.send("{\"sub\":\"trader."+code+"\"}");
//            stockSocketFive.send(new Gson().toJson(new SocketSendBean(Constans.FIVE_PUSH)));
        }
        this.code=code;

    }

    public void sendCode(String code) {

        initSocket(code);
    }


    public void closeWebSocket() {
        stockSocket.close();
        stockSocket = null;
    }

}
